//25 hard
function reverseKGroup(head, k) {
  let prev = { val: 0, next: head };
  let phead = prev;
  let cur = head;
  while (cur != null) {
    for (let i = 0; i < k; i++) {
      if (cur === null) {
        return phead.next;
      }
      if (i === k - 1) {
        const temp = cur.next;
        cur.next = null;
        cur = temp;
      } else {
        cur = cur.next;
      }
    }
    prev.next = reverseList(prev.next);
    for (let i = 0; i < k; i++) {
      prev = prev.next;
    }
    prev.next = cur;
  }
  return phead.next;

  function reverseList(head) {
    if (head == null) return head;
    const list = {};
    let current = list;
    function reverse(node) {
      if (node === null) {
        return;
      }
      reverse(node.next);
      current.val = node.val;
      current.next = {};
      if (node !== head) current = current.next;
    }
    reverse(head);
    current.next = null;
    return list;
  }
}
console.log(
  reverseKGroup(
    {
      val: 1,
      next: {
        val: 2,
        next: null,
      },
    },
    2
  )
);
console.log(1);
